package model;

/**
 *
 * @author Dustin
 */
public class ReceiveWindow extends Thread {

    private int requestNumber;
    private SendWindow sendWindow;
    private HigherLayer higherLayer;
    private Queue inputQueue;

    public ReceiveWindow(Queue aQueue, HigherLayer aHigherLayer) {
        inputQueue = aQueue;
        higherLayer = aHigherLayer;
    }

    public void run() {
        while(true) {
            if(!inputQueue.isEmpty()) {
                Packet p = (Packet) inputQueue.dequeue();
                if(p.isAck()) {
                    sendWindow.removePacket(p);
                } else if (p.getSeq() == requestNumber) {
                    higherLayer.receive(p);
                    Packet ack = new Packet(true, requestNumber);
                    sendWindow.getOutputQueue().enqueue(ack);
                    System.out.println("Send ACK " + ack.getSeq());
                    requestNumber++;
                } else {
                    Packet ack = new Packet(true, requestNumber-1);
                    sendWindow.getOutputQueue().enqueue(ack);
                    System.out.println("RESend ACK " + ack.getSeq());
                }
            }
            yield();
        }
    }

    public int getRequestNumber() {
        return requestNumber;
    }

    public void setSendWindow(SendWindow aSendWindow) {
        sendWindow = aSendWindow;
    }
}
